using System;
using UnityEngine;
using UnityEngine.UI;
using Yoozoo.Gameplay;

namespace Gameplay.RTS.Hud
{
    public class FlyTextController : MonoBehaviour
    {
        private Text m_text;
        private Animation m_flyAnimation;
        private CanvasGroup m_canvasGroup;
        private float m_offsetX;
        public float startTime;
        public string numberStr;
        public bool isPlayed;

        public void Initialize()
        {
            if (m_text == null)
            {
                m_text = GetComponentInChildren<Text>();
                m_text.text = string.Empty;
            }

            if (m_flyAnimation == null)
            {
                m_flyAnimation = GetComponentInChildren<Animation>();
            }

            if (m_canvasGroup == null)
            {
                m_canvasGroup = GetComponentInChildren<CanvasGroup>();
            }
        }

        private void Update()
        {
            if (isPlayed)
            {
                return;
            }

            if (TimeUtils.GetClientTickTime() >= this.startTime)
            {
                
                m_text.text = this.numberStr;
                if (m_flyAnimation != null)
                {
//                    m_flyAnimation.Play("ani_ui_FlyText");
                }

                this.isPlayed = true;
            }
        }

        public void Play(float startTime, string numberStr, float speed)
        {
            SetSpeed(speed);
            this.startTime = startTime;
            this.numberStr = numberStr;
            m_text.text = numberStr;
            this.isPlayed = false;
            this.m_canvasGroup.alpha = 0;
            this.SetActive(true);
        }

        public void PlayFadeOut()
        {
            if (m_flyAnimation != null)
            {
                m_flyAnimation.Play("ani_ui_FlyText2");
            }
        }

        public void SetOffsetX(float x)
        {
            m_offsetX = x;
            SetPositionX(0);
        }
        
        public float GetOffsetX()
        {
            
            return this.transform.localPosition.x;
        }

        public void SetPositionX(float middleOffset)
        {
            this.transform.localPosition=  new Vector3(m_offsetX - middleOffset, -50f, 0);
        }

        public float GetWidth()
        {
            if (this.numberStr.Equals("1"))
            {
                return 24.0f;
            }
            else if (this.numberStr.Equals("4"))
            {
                return 36.0f;
            }

            return 32.0f;
        }

        public void SetSpeed(float speed)
        {
            m_flyAnimation["ani_ui_FlyText"].speed = speed;
//            m_flyAnimation["ani_ui_FlyText2"].speed = speed;
        }
    }
}